//
//  PublishHistoryViewController.m
//  InviteJob
//
//  Created by chirui on 2017/11/7.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "PublishHistoryViewController.h"
#import "PublishHistoryTVCell.h"
#import "BuilsServerDetailsViewController.h"

@interface PublishHistoryViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    UITableView * _tableView;
    NSMutableArray * _dataArray;
    
    int _page;
    int _totailPage;
    
    UIView * noBodyView;
    
    NSString *_build_service_top;
}

@end

@implementation PublishHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _page =1;

    TitleView(@"发布历史");
    [self creatTableView];
    
    _dataArray = @[].mutableCopy;
//    noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-150, 200, 200) andMessageStr:@"没有相关消息！" onView:nil];
    
    [self getMessageListData];

}

-(void)creatTableView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.dataSource =self;
    _tableView.delegate =self;
    _tableView.separatorStyle = UITableViewCellEditingStyleNone;
    _tableView.backgroundColor = strColor(@"f6f6f6");
    [self.view addSubview:_tableView];
  
    [_tableView registerNib:[UINib nibWithNibName:[PublishHistoryTVCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[PublishHistoryTVCell reuseIdentifier]];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
  
            _page = 1;
            [self getMessageListData];
        
    }];
    _tableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
            _page ++;
            [self getMessageListData];
        
    }];
    
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    
    if (_dataArray.count>10) {
        _tableView.mj_footer.hidden = NO;
    }else{
        _tableView.mj_footer.hidden = YES;
    }

    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
   
    
    return 0.01;
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //左滑删除
    return UITableViewCellEditingStyleDelete;
    
}
//修改左滑删除按钮的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
     
            _page = 1;//
            NSDictionary * dic = _dataArray[indexPath.row];
            [self deledateMessageRequestFor:dic[@"service_id"]];
            
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
    PublishHistoryTVCell * cell = [tableView dequeueReusableCellWithIdentifier:[PublishHistoryTVCell reuseIdentifier]];
    
    cell.titleName.text  = dic[@"title"];
    cell.titleName.numberOfLines = 2;
    cell.timeLabel.text  = dic[@"create_time"];
    cell.statisBtn.tag = 100+indexPath.row;
    cell.statisBtn.layer.cornerRadius = 3;
    cell.statisBtn.layer.masksToBounds = YES;
    if ([dic[@"confirm_status"] isEqualToString:@"wait"]) {
        
        [cell.statisBtn setTitle:@"待审核" forState:UIControlStateNormal];
        [cell.statisBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        cell.statisBtn.layer.borderWidth = 0.5;
        cell.statisBtn.layer.borderColor = [UIColor grayColor].CGColor;
    }else if ([dic[@"confirm_status"] isEqualToString:@"refuse"]){
    
        [cell.statisBtn setTitle:@"审核拒绝" forState:UIControlStateNormal];
        [cell.statisBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        cell.statisBtn.layer.borderWidth = 0.5;
        cell.statisBtn.layer.borderColor = [UIColor grayColor].CGColor;
    }else {
        
        [cell.statisBtn setTitle:@"置顶" forState:UIControlStateNormal];
         [cell.statisBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        cell.statisBtn.layer.borderWidth = 0.5;
        cell.statisBtn.layer.borderColor = [UIColor orangeColor].CGColor;
        [cell.statisBtn addTarget:self action:@selector(statisBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
   
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    BuilsServerDetailsViewController * details =[[BuilsServerDetailsViewController alloc]init];
    details.hidesBottomBarWhenPushed = YES;
    details.severID = dic[@"service_id"];
    [self.navigationController pushViewController:details animated:YES];

}

-(void)statisBtnClick:(UIButton *)btn{
     NSDictionary * dic = _dataArray[btn.tag-100];
    [SHJudgeTools showAlertCntrollerWithViewController:self alertControllerStyle:UIAlertControllerStyleAlert title:@"温馨提示" message:[NSString stringWithFormat:@"需%@点券可置顶",_build_service_top] CallBackBlock:^(NSInteger btnIndex) {
        
        if (btnIndex==1) {
           [self setTopRequestFor:dic[@"service_id"]];
        }
        
    } cancelButtonTitle:@"考虑一下" destructiveButtonTitle:@"购买" otherButtonTitles:nil];

  
    
}

-(void)getMessageListData{
    
    isUser
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{@"user_id":user.user_id,
                           @"token":user.token,
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10",
                           @"type":USER_DEFAULTGet(@"server")
                           };
    
    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(publish_history_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [responseObject[@"datas"][@"total_page"]  intValue];
            _build_service_top = responseObject[@"datas"][@"build_service_top"];
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    [self hideNoDataView];
                    if (_dataArray.count<10) {
                        
                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;
                    [self shopNoDataViewBackgroundColor:[UIColor clearColor] withImage:@"img_home_no_news" withLabelMsg:@"没有任何数据" withButton:@"" isY:0];
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
    
    
}

-(void)deledateMessageRequestFor:(NSString *)str {
    
    isUser
    NSDictionary * dic = @{@"user_id":user.user_id,
                           @"token":user.token,
                           @"service_id":str
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(deledate_history_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            SHuiMBhudTextTimeStr(@"删除成功");
            _page = 1;
            [self getMessageListData];
        }
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
}



-(void)setTopRequestFor:(NSString *)str {
    
    isUser
    NSDictionary * dic = @{@"user_id":user.user_id,
                           @"token":user.token,
                           @"service_id":str
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(setTop_service_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
             _page = 1;
            [self getMessageListData];
        }
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
}

@end
